<template>
  <div class="admin-comments-container">
    <el-card class="header-card">
      <div class="header-content">
        <h2><el-icon><ChatLineSquare /></el-icon> 评价管理</h2>
        <div class="header-info">
          <el-tag type="info">查看和管理用户评价</el-tag>
        </div>
      </div>
    </el-card>

    <!-- 标签页切换 -->
    <el-card class="tabs-card">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="菜品评价" name="dish">
          <template #label>
            <span class="tab-label">
              <el-icon><Dish /></el-icon>
              菜品评价
            </span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="订单评价" name="order">
          <template #label>
            <span class="tab-label">
              <el-icon><List /></el-icon>
              订单评价
            </span>
      </template>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-card class="search-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchForm.orderId"
            placeholder="订单ID"
            clearable
            @clear="handleSearch"
            v-if="activeTab === 'order'"
          />
          <el-input
            v-model="searchForm.dishId"
            placeholder="菜品ID"
            clearable
            @clear="handleSearch"
            v-if="activeTab === 'dish'"
          />
        </el-col>
        <el-col :span="6">
          <el-input
            v-model="searchForm.dishId"
            placeholder="菜品ID"
            clearable
            @clear="handleSearch"
            v-if="activeTab === 'order'"
          />
          <el-input
            v-model="searchForm.userId"
            placeholder="用户ID"
            clearable
            @clear="handleSearch"
            v-if="activeTab === 'dish'"
          />
        </el-col>
        <el-col :span="4">
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
        </el-col>
      </el-row>
    </el-card>

    <el-card v-loading="loading">
      <el-table :data="filteredComments" stripe style="width: 100%; height: 600px;">
        <el-table-column prop="commentId" label="ID" width="80" />
        <el-table-column prop="orderId" label="订单ID" width="100" v-if="activeTab === 'order'">
          <template #default="{ row }">
            {{ row.orderId || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="用户" width="120">
          <template #default="{ row }">
            {{ row.user?.nickname || '未知' }}
          </template>
        </el-table-column>
        <el-table-column label="菜品" min-width="120">
          <template #default="{ row }">
            {{ row.dish?.dishName || '未知' }}
          </template>
        </el-table-column>
        <el-table-column label="评分" width="150">
          <template #default="{ row }">
            <el-rate v-model="row.rating" disabled size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="commentContent" label="评论内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="commentStatus" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.commentStatus === '0' ? 'success' : 'info'">
              {{ row.commentStatus === '0' ? '显示' : '隐藏' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row.commentId)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { Search, Delete, ChatLineSquare, Dish, List } from '@element-plus/icons-vue';
import { getAllComments, getCommentsByOrderId, deleteComment } from '@/api/comment';
import { getUserById } from '@/api/user';
import { getDishById } from '@/api/dish';
import type { Comment } from '@/types';
import { ElMessage, ElMessageBox } from 'element-plus';

const loading = ref(false);
const comments = ref<Comment[]>([]);
const activeTab = ref('dish');

const searchForm = reactive({
  orderId: '',
  dishId: '',
  userId: ''
});

// 根据当前标签页过滤评论
const filteredComments = computed(() => {
  if (activeTab.value === 'dish') {
    // 菜品评价：orderId为null或空
    return comments.value.filter(comment => !comment.orderId);
  } else {
    // 订单评价：orderId不为null
    return comments.value.filter(comment => comment.orderId);
  }
});

// 加载评论列表
const loadComments = async () => {
  loading.value = true;
  try {
    const response = await getAllComments();
    if (response.operateResult === 'SUCC' && response.data) {
      // 加载每个评论的用户和菜品信息
      const commentsWithDetails = await Promise.all(
        response.data.map(async (comment) => {
          const userRes = await getUserById(comment.userId);
          const dishRes = await getDishById(comment.dishId);
          return {
            ...comment,
            user: userRes.operateResult === 'SUCC' ? userRes.data : undefined,
            dish: dishRes.operateResult === 'SUCC' ? dishRes.data : undefined
          };
        })
      );
      comments.value = commentsWithDetails.sort((a, b) => {
        return new Date(b.createTime || '').getTime() - new Date(a.createTime || '').getTime();
      });
    } else {
      comments.value = [];
    }
  } catch (error) {
    ElMessage.error('加载评论失败');
    comments.value = [];
  } finally {
    loading.value = false;
  }
};

// 标签页切换
const handleTabChange = (tabName: string) => {
  activeTab.value = tabName;
  // 清空搜索条件
  searchForm.orderId = '';
  searchForm.dishId = '';
  searchForm.userId = '';
};

// 搜索评论
const handleSearch = async () => {
  if (!searchForm.orderId && !searchForm.dishId && !searchForm.userId) {
    await loadComments();
    return;
  }
  
  loading.value = true;
  try {
    let response;
    if (activeTab.value === 'order' && searchForm.orderId) {
      response = await getCommentsByOrderId(Number(searchForm.orderId));
    } else {
      await loadComments();
      // 根据搜索条件过滤
      if (searchForm.dishId) {
        comments.value = comments.value.filter(c => c.dishId === Number(searchForm.dishId));
      }
      if (searchForm.userId) {
        comments.value = comments.value.filter(c => c.userId === Number(searchForm.userId));
      }
      loading.value = false;
      return;
    }
    
    if (response && response.operateResult === 'SUCC' && response.data) {
      const commentsWithDetails = await Promise.all(
        response.data.map(async (comment) => {
          const userRes = await getUserById(comment.userId);
          const dishRes = await getDishById(comment.dishId);
          return {
            ...comment,
            user: userRes.operateResult === 'SUCC' ? userRes.data : undefined,
            dish: dishRes.operateResult === 'SUCC' ? dishRes.data : undefined
          };
        })
      );
      comments.value = commentsWithDetails;
    } else {
      comments.value = [];
    }
  } catch (error) {
    ElMessage.error('搜索失败');
  } finally {
    loading.value = false;
  }
};

// 格式化时间 - 显示完整日期时间
const formatTime = (time?: string) => {
  if (!time) return '';
  const date = new Date(time);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  });
};


// 删除评论
const handleDelete = (commentId: number) => {
  ElMessageBox.confirm('确定要删除该评论吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteComment(commentId);
      if (response.operateResult === 'SUCC') {
        ElMessage.success('删除成功');
        await loadComments();
      } else {
        ElMessage.error(response.errorMsg || '删除失败');
      }
    } catch (error: any) {
      ElMessage.error(error.message || '删除失败');
    }
  }).catch(() => {});
};


onMounted(() => {
  loadComments();
});
</script>

<style scoped>
.admin-comments-container {
  animation: fadeIn 0.5s ease-out;
  position: relative;
  z-index: 1;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.header-card {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content h2 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #303133;
}

.header-info {
  display: flex;
  align-items: center;
}

.tabs-card {
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

/* 标签页样式 */
:deep(.el-tabs) {
  background: transparent;
}

:deep(.el-tabs__header) {
  margin: 0;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(248, 250, 252, 0.9) 100%);
  border-radius: 12px;
  padding: 8px 20px;
}

:deep(.el-tabs__nav-wrap) {
  padding: 0;
}

:deep(.el-tabs__nav) {
  border: none;
}

:deep(.el-tabs__item) {
  border: none;
  border-radius: 8px;
  margin: 8px 4px;
  padding: 0 32px;
  height: 48px;
  line-height: 48px;
  font-weight: 600;
  transition: all 0.3s ease;
  background: transparent;
  min-width: 140px;
  text-align: center;
}

:deep(.el-tabs__item:hover) {
  background: rgba(102, 126, 234, 0.1);
  color: #667eea;
}

:deep(.el-tabs__item.is-active) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
}

:deep(.el-tabs__active-bar) {
  display: none;
}

.tab-label {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 100%;
}

/* 美化卡片样式 */
:deep(.el-card) {
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: none;
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.9);
}

/* 美化按钮样式 */
:deep(.el-button) {
  border-radius: 12px;
  font-weight: 600;
  transition: all 0.3s ease;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
}

:deep(.el-button--primary:hover) {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.4);
}

:deep(.el-button--danger) {
  background: linear-gradient(135deg, #f56565 0%, #e53e3e 100%);
  border: none;
  box-shadow: 0 4px 16px rgba(245, 101, 101, 0.3);
}

:deep(.el-button--danger:hover) {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(245, 101, 101, 0.4);
}

/* 美化表格样式 */
:deep(.el-table) {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

:deep(.el-table__header) {
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
}

:deep(.el-table th) {
  background: transparent;
  color: #4a5568;
  font-weight: 600;
  border-bottom: 2px solid #e2e8f0;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f1f5f9;
}

:deep(.el-table tr:hover > td) {
  background-color: rgba(102, 126, 234, 0.05);
}

/* 美化标签样式 */
:deep(.el-tag) {
  border-radius: 8px;
  font-weight: 600;
  border: none;
}

:deep(.el-tag--success) {
  background: linear-gradient(135deg, #48bb78 0%, #38a169 100%);
  color: white;
}

:deep(.el-tag--info) {
  background: linear-gradient(135deg, #4299e1 0%, #3182ce 100%);
  color: white;
}

/* 美化输入框样式 */
:deep(.el-input__wrapper) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  border-color: #667eea;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 美化评分组件 */
:deep(.el-rate) {
  display: flex;
  align-items: center;
}

:deep(.el-rate__icon) {
  font-size: 16px;
  color: #f7ba2a;
}

/* 美化消息提示 */
:deep(.el-message) {
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10px);
}

:deep(.el-message--success) {
  background: linear-gradient(135deg, rgba(72, 187, 120, 0.9) 0%, rgba(56, 161, 105, 0.9) 100%);
  border: none;
}

:deep(.el-message--error) {
  background: linear-gradient(135deg, rgba(245, 101, 101, 0.9) 0%, rgba(229, 62, 62, 0.9) 100%);
  border: none;
}

:deep(.el-message--warning) {
  background: linear-gradient(135deg, rgba(237, 137, 54, 0.9) 0%, rgba(221, 107, 32, 0.9) 100%);
  border: none;
}
</style>
